package connections;

import java.io.* ;

import serverManger.Server;
import message.Message;
import message.MessageType;
/**
 * this class is in charge of running the dialog server->client
 * @author ran
 *
 */
public class ReceiveMessageProtocol {
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private MessageHandler handler;
	private Server server;

	/**
	 * constructor of the class, reset the members of the class
	 * @param in - input stream object
	 * @param out - output stream object
	 */
	public ReceiveMessageProtocol(ObjectInputStream in, ObjectOutputStream out){
		this.in=in;
		this.out=out;
		handler = new MessageHandler();
		server = Server.getServerInst();
		
	}
	/**
	* override the the run method of class runnable
	*/
	public void run(){
		Message message=null,messageToClient=null;
		try {			
			//loop that implements the dialog server - > client
			while((message = (Message)in.readObject()).getType()!=MessageType.STOP_COMUNICATION || (message=server.getNextMessage(handler.getComp()))!=null){
				if(messageToClient!=null&&messageToClient.getType()==MessageType.STOP_SYNC)
					break;
				messageToClient=handler.interpretMessage(message);
				//send message to the client
				out.writeObject(messageToClient);
				
			}
		} 
		catch (ClassNotFoundException e){
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
}


